﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

namespace Rail.Commons.SerializeHelper
{
    public class ExcelHelper
    {
        /// <summary>
        /// 通过NPOI获取Excel列头明细集合
        /// 支持2003、2007版本
        /// </summary>
        /// <param name="Path">Excel文件路径</param>
        /// <returns></returns>
        public static Dictionary<string, bool> GetColumnsByReadExcel(string Path)
        {
            Dictionary<string, bool> dict = new Dictionary<string, bool>();
            if (!string.IsNullOrEmpty(Path) && File.Exists(Path))
            {
                try
                {
                    IWorkbook workbook = null;  //新建IWorkbook对象
                    FileStream fileStream = new FileStream(Path, FileMode.Open, FileAccess.Read);
                    if (Path.IndexOf(".xlsx") > 0) // 2007版本
                    {
                        workbook = new XSSFWorkbook(fileStream);  //xlsx数据读入workbook
                    }
                    else if (Path.IndexOf(".xls") > 0) // 2003版本
                    {
                        workbook = new HSSFWorkbook(fileStream);  //xls数据读入workbook
                    }
                    ISheet sheet = workbook.GetSheetAt(0);  //获取第一个工作表
                    IRow row1 = sheet.GetRow(0);            //新建当前工作表行数第一行
                    for (int i = 0; i < row1.Cells.Count; i++)
                    {
                        //当该行前景色为
                        dict[row1.Cells[i].ToString()] = row1.Cells[i].CellStyle.FillForegroundColor != 64 ? true : false;
                    }

                    fileStream.Close();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    System.Windows.Forms.MessageBox.Show("当前Excel文件被占用，打开失败!");
                }
            }
            return dict;
        }

    }
}
